
package android.persist.op.sqlite;

import static android.persist.op.sqlite.SQLLogging.SQL_LOG_TAG;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.persist.config.ClassConfig;
import android.persist.op.ExistsStowage;
import android.util.Log;

/**
 * An operation that checks to see if stowage exists for a specific class.
 * 
 * @author Richard Schilling
 * @param <OT> the type of class to check stowage for.
 */
public class SQLiteExistsStowage<OT> extends ExistsStowage<Class<OT>, Boolean> {

    /**
     * The database that this operation will be applied against.
     * 
     * @since 1.0
     */
    private final SQLiteDatabase mDatabase;

    /**
     * Configuration information about the operation's type.
     * 
     * @since 1.0
     */
    private final ClassConfig<OT> mConfig;

    public SQLiteExistsStowage(SQLiteDatabase db, Class<OT> c) {
        super(c);
        this.mDatabase = db;
        mConfig = (ClassConfig<OT>) ClassConfig.getConfig(c);

    }

    @Override
    public Boolean call() {
        if (!mDatabase.isOpen()) {
            throw new IllegalStateException("database is closed");
        }

        StringBuilder query = new StringBuilder();
        query.append("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='");
        query.append(mConfig.storageName);
        query.append("'");

        if (Log.isLoggable(SQL_LOG_TAG, Log.DEBUG)) {
            Log.d(SQL_LOG_TAG,
                    query.toString());
        }
        SQLiteStatement stmt = mDatabase
                .compileStatement(query.toString());
        return stmt.simpleQueryForLong() == 1;
    }
}
